<?php
/**
 * @author Oliver Leisalu
 * @package WapBilling
 * 
 * See sample.php for usage instructions.
 * 
 * Simulating operator and phoneNumber: http://site.com/?msisdn=SAMPLE_NUM&resolveTo=OPERATOR
 * Set both to "auto" to stop simulation. (Notice that buying is disabled in simulation mode for security purposes!)
 *
 */
class WapBilling {
	
	/**
	 * @var WapBillingOperator
	 */
	private static $operatorHandler = NULL;
	/**
	 * Accepts all payments as successful. Be careful with this! Useful for making unit tests.
	 * @var Bool
	 */
	public static $acceptAllPayments = false;
	/**
	 * Operator name [elisa|tele2|emt]
	 *
	 * @var String
	 */
	private static $operator = NULL;
	
	/**
	 * Creating instances of WapBilling is not allowed
	 */
	private function __construct() {}

	/**
	 * Makes payment
	 *
	 * Returns 
	 * <ul>
	 * <li> 0 - success  </li>
	 * <li> 1 - failure </li>
	 * <li> 2 - not allowed </li>
	 * <li> 3 - system error </li>
	 * <li> 4 - unable to save log entry  </li>
	 * <li> 5 - payment made but updating log entry failed  </li>
	 * <li> 6 - unable to resolve operator  </li>
	 * <li> 7 - bad uid </li>
	 * <li> 8 - buying is not allowed in test mode </li>
	 * </ul>
	 * 
	 * @param Float $price
	 * @param String $description
	 * @return Int
	 */
	public static function pay( $price, $description, $uid = 0 ) {
		
		
		if( self::$acceptAllPayments === true or $_SERVER['SERVER_NAME'] == 'localhost' ) {
			return 0;
		}
		
		if( ($_SESSION['wapBilling']['msisdn'] or $_SESSION['wapBilling']['resolveTo']) && !$_SESSION['wapBilling']['tele2Web'] ) {
			return 8;
		}
		
		if( self::resolve() === false ) {
			return 6;
		}
		
		// test that uid is ok
		if( !(is_numeric($uid) && (int)$uid == $uid && $uid < 4294967295) ) {
			return 7;
		}
			
		$description = str_replace('ö', 'o', $description);
		$description = str_replace('ä', 'a', $description);
		$description = str_replace('ü', 'u', $description);
		$description = str_replace('õ', 'o', $description);
			
		$description = str_replace('Ö', 'O', $description);
		$description = str_replace('Ä', 'A', $description);
		$description = str_replace('Ü', 'U', $description);
		$description = str_replace('Õ', 'O', $description);
			
		$description = htmlspecialchars($description);
		
		// create log entry
		$log = new WapBillingLog();
		$log->uid = (int)$uid;
		$log->price = (float)$price;
		$log->description = $description;
		$log->currency = 'EUR';
		$log->status = 2;
		$log->phoneNr = self::getPhoneNr();
		$log->operator = self::getOperator();
		
		if( !$log->save() ) {
			return 4;
		}
		// ------------------
		
		
		$result = self::$operatorHandler->pay( $price, $description, $uid, $log->id );
		
		
		// update log entry
		$log->result = self::getLastError();
		$log->status = (int)$result;
		if( !$log->save() ) {
			// do some failure handling
			// this should never fail...
		}
		// ------------------
		
		return $result;
	}
	
	public static function getLastError() {
		if( self::$operatorHandler )
			return self::$operatorHandler->getLastError();
		else
			return 'Unknown operator';
	}
	
	
	public static function getOperator() {
		return self::$operator;
	}

	public static function isElisa() {
		return self::$operator == 'elisa';
	}
	
	public static function isEmt() {
		return self::$operator == 'emt';
	}
	
	public static function isTele2() {
		return self::$operator == 'tele2';
	}
	
	public static function isUnknown() {
		return self::$operator == '';
	}
	
	public static function getPhoneNr() {
		return self::getMsisdn();
	}
	
	public static function getMsisdn() {
		
		if( $_GET['msisdn'] == 'auto' ) {
			unset($_SESSION['wapBilling']['msisdn']);
		} else if( $_GET['msisdn'] ) {
			$_SESSION['wapBilling']['msisdn'] = $_GET['msisdn'];
		}
		
		if( $_SESSION['wapBilling']['msisdn'] )
			return $_SESSION['wapBilling']['msisdn'];
		
		if( is_object(self::$operatorHandler) === true )
			return self::$operatorHandler->getMsisdn();
		else
			return '';
	}
	
	public static function resolve( $configFilePath  = NULL ) {
		
		
		$ip = $_SERVER['REMOTE_ADDR'];
		
		// ELISA
		if( strpos($ip,'194.204.2.6') !== false ) {
			$resolved = 'elisa';
		}
		
		// EMT
		if( (strpos($ip,'217.71.32.') !== false ) ||  (strpos($ip,'217.71.35.') !== false ) || (strpos($ip,'46.131.') !== false ) ) {
			$resolved = 'emt';
		}
		
		// TELE2
		$host = gethostbyaddr( $ip );
		if( strpos($host,'tele2') > 0 or strpos($host,'swip.net') > 0 ){
			$resolved = 'tele2';
		}
		
		//if( $resolved == '' )
		//	$resolved = 'tele2';
		
		if( $_GET['resolveTo'] == 'auto' ) {
			unset($_SESSION['wapBilling']['resolveTo']);
		} else if( $_GET['resolveTo'] ) {
			$resolved = $_GET['resolveTo'];
		} else if( $_SESSION['wapBilling']['resolveTo'] ) {
			$resolved = $_SESSION['wapBilling']['resolveTo'];
		}
		
		$log = new DomDBLogger('COOKIE');
		$log->log($resolved, serialize($_COOKIE));
		
		switch( $resolved ) {
			case 'emt':
				self::$operatorHandler = new WapBilling_Emt( $configFilePath );
				self::$operator = 'emt';
			break;
			case 'tele2':
				self::$operatorHandler = new WapBilling_Tele2( $configFilePath );
				self::$operator = 'tele2';
			break;
			case 'tele2new':
				self::$operatorHandler = new WapBilling_Tele2New( $configFilePath );
				self::$operator = 'tele2New';
			break;
			case 'elisa':
				self::$operatorHandler = new WapBilling_Elisa( $configFilePath );
				self::$operator = 'elisa';
			break;
			default:
				self::$operatorHandler = false;
				self::$operator = '';
			break;
		}
		
		if( $_GET['resolveTo'] ) {
			$_SESSION['wapBilling']['resolveTo'] = self::$operator;
		}
		
		return is_object(self::$operatorHandler);
	}
}
WapBilling::resolve();
?>